﻿namespace Vdc.Grid
{
    using Vdc.Interface;
    using System;
    using System.IO;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    internal class GridHeader : WebControl, INamingContainer
    {
        private Vdc.Grid.Grid grid;
        private HtmlContainer innerHeader;

        public GridHeader(Vdc.Grid.Grid _grid)
        {
            this.grid = _grid;
            this.ID = this.GetHeaderID();
        }

        protected virtual GridDataControlFieldCell CreateCell(Column field)
        {
            GridDataControlFieldCell cell = new GridDataControlFieldCell(field);
            if (field.Visible)
            {
                cell.CssClass = !field.Wrap ? "ob_gC" : "ob_gCW";
            }
            else
            {
                cell.CssClass = !field.Wrap ? "ob_gC_I" : "ob_gCW_I";
            }
            if (field.Index == this.grid.IndexOfFirstVisibleColumn)
            {
                cell.CssClass = cell.CssClass + " ob_gC_Fc";
            }
            else if (field.Index == this.grid.IndexOfLastVisibleColumn)
            {
                cell.CssClass = cell.CssClass + " ob_gC_Lc";
            }
            if (this.grid.IsDesignTimeRender && this.grid.UseEmbeddedImages)
            {
                if (this.grid.AllowGrouping)
                {
                    cell.Style["background-image"] = "url(" + this.grid.ImagesURL.Header + ")";
                }
                else
                {
                    cell.Style["background-image"] = "url(" + this.grid.ImagesURL.HeaderWithoutGrouping + ")";
                }
            }
            if (field.Width.IndexOf("%") == -1)
            {
                cell.Width = Unit.Pixel(int.Parse(field.Width));
            }
            else
            {
                cell.Width = Unit.Percentage((double) int.Parse(field.Width.Replace("%", "")));
            }
            if (this.grid.IsDesignTimeRender)
            {
                if (!field.Visible)
                {
                    cell.Style["display"] = "none";
                    cell.Width = Unit.Pixel(0);
                }
                cell.Attributes["_designerRegion"] = field.Index.ToString();
            }
            HtmlContainer child = new HtmlContainer();
            HtmlContainer container2 = new HtmlContainer();
            child.CssClass = "ob_gCc1";
            if (string.IsNullOrEmpty(field.HeaderAlign) || (field.HeaderAlign.ToLower() == "left"))
            {
                container2.CssClass = "ob_gCc2";
            }
            else if (field.HeaderAlign.ToLower() == "center")
            {
                container2.CssClass = "ob_gCc2C";
            }
            else
            {
                container2.CssClass = "ob_gCc2R";
            }
            child.Controls.Add(container2);
            cell.Controls.Add(child);
            if ((field is CheckBoxSelectColumn) && ((CheckBoxSelectColumn) field).ShowHeaderCheckBox)
            {
                if (((CheckBoxSelectColumn) field).ControlType == GridControlType.Standard)
                {
                    CheckBox box = new CheckBox();
                    container2.Controls.Add(box);
                }
                else
                {
                    string str = "ob_chkSel" + this.grid.GridID + "_" + field.Index.ToString();
                    HiddenField field2 = new HiddenField {
                        Value = str
                    };
                    container2.Controls.Add(field2);
                    VdcCheckBox box2 = new VdcCheckBox
                    {
                        ID = str
                    };
                    container2.Controls.Add(box2);
                }
            }
            string str2 = !string.IsNullOrEmpty(field.HeaderText) ? GridEncodingHelper.XMLCdataEncode(field.HeaderText) : GridEncodingHelper.XMLCdataEncode(field.DataField);
            if (string.IsNullOrEmpty(field.TemplateSettings.HeaderTemplateId))
            {
                container2.Text = str2;
            }
            else
            {
                GridTemplate template = null;
                GridRuntimeTemplate template2 = null;
                if (this.grid.Templates.GetById(field.TemplateSettings.HeaderTemplateId) is GridRuntimeTemplate)
                {
                    GridRuntimeTemplate runtimeTemplateById = this.grid.Templates.GetRuntimeTemplateById(field.TemplateSettings.HeaderTemplateId);
                    if (runtimeTemplateById == null)
                    {
                        throw new InvalidTemplateIDException(field.TemplateSettings.HeaderTemplateId);
                    }
                    template2 = (GridRuntimeTemplate) runtimeTemplateById.Clone();
                }
                else
                {
                    GridTemplate byId = this.grid.Templates.GetById(field.TemplateSettings.HeaderTemplateId);
                    if (byId == null)
                    {
                        throw new InvalidTemplateIDException(field.TemplateSettings.HeaderTemplateId);
                    }
                    template = (GridTemplate) byId.Clone();
                }
                if (template != null)
                {
                    template.Container.Value = (str2 != string.Empty) ? str2.Replace("\r\n", "<br />") : "&#160;";
                    container2.Controls.Add(template);
                    template.ForceDataBind();
                }
                if (template2 != null)
                {
                    template2.Container.Value = (str2 != string.Empty) ? str2.Replace("\r\n", "<br />") : "&#160;";
                    template2.DataBind();
                    container2.Controls.Add(template2);
                }
            }
            child.Controls.Add(this.CreateSortingImage(field));
            return cell;
        }

        protected virtual void CreateCellSeparator(string width, bool visible)
        {
            HtmlContainer child = new HtmlContainer {
                Text = "&#160;",
                CssClass = "ob_gCS"
            };
            child.Style["left"] = width;
            if (!visible || this.grid.HasColumnsWithFixedAndPercentageWidth)
            {
                child.Style["display"] = "none";
            }
            HtmlContainer container2 = new HtmlContainer {
                Text = "&#160;"
            };
            child.Controls.Add(container2);
            this.innerHeader.Controls.Add(child);
        }

        protected override void CreateChildControls()
        {
            this.CssClass = ((!this.grid.AllowGrouping && !this.grid.displayTopFooter) && string.IsNullOrEmpty(this.grid.TemplateSettings.HeadingTemplateId)) ? this.grid.CssSettings.CSSHeaderContainerWithoutGrouping : this.grid.CssSettings.CSSHeaderContainer;
            this.innerHeader = new HtmlContainer();
            this.innerHeader.CssClass = "ob_gHICont";
            Table child = new Table {
                CssClass = this.grid.CssSettings.CSSHeader
            };
            child.Attributes["cellspacing"] = "0";
            child.Attributes["cellpadding"] = "0";
            child.Width = Unit.Percentage(100.0);
            this.innerHeader.Controls.Add(child);
            this.Controls.Add(this.innerHeader);
            GridRow row = new GridRow(0, 0, GridRowType.Header, DataControlRowState.Normal) {
                CssClass = "ob_gHR"
            };
            child.Controls.Add(row);
            int num = 0;
            int num2 = 0;
            foreach (Column column in this.grid.Columns)
            {
                row.Controls.Add(this.CreateCell(column));
                bool visible = column.Visible;
                if (num < (this.grid.Columns.Count - 1))
                {
                    if (column.Width.IndexOf("%") == -1)
                    {
                        this.CreateCellSeparator(((num2 + int.Parse(column.Width))).ToString() + "px", visible);
                    }
                    else
                    {
                        this.CreateCellSeparator(((num2 + int.Parse(column.Width.Replace("%", "")))).ToString() + "%", visible);
                    }
                }
                if (column.Visible)
                {
                    num2 += int.Parse(column.Width.Replace("%", ""));
                }
                num++;
            }
            GridRowEventArgs e = new GridRowEventArgs(row);
            this.grid.OnRowCreated(e);
            base.CreateChildControls();
        }

        protected virtual HtmlContainer CreateSortingImage(Column field)
        {
            Image child = new Image();
            child.Attributes["alt"] = "";
            if (field.SortOrder == SortOrderType.Asc)
            {
                child.ImageUrl = this.grid.ImagesURL.Sorting_Asc;
            }
            else if (field.SortOrder == SortOrderType.Desc)
            {
                child.ImageUrl = this.grid.ImagesURL.Sorting_Desc;
            }
            else if (!string.IsNullOrEmpty(field.DataField) && this.grid.AllowSorting)
            {
                child.ImageUrl = this.grid.ImagesURL.Placeholder;
            }
            else
            {
                child.ImageUrl = this.grid.ImagesURL.PlaceholderEmpty;
            }
            HtmlContainer container = new HtmlContainer {
                CssClass = "ob_gHSI"
            };
            container.Controls.Add(child);
            if (this.grid.IsDesignTimeRender)
            {
                container.CssClass = container.CssClass + " ob_gHSI_F_D";
            }
            return container;
        }

        internal virtual void Export(Html32TextWriter oHtmlTextWriter)
        {
            if (this.innerHeader == null)
            {
                this.EnsureChildControls();
            }
            TableRow row = this.innerHeader.Controls[0].Controls[0] as TableRow;
            TableRow child = new TableRow();
            foreach (int num in this.grid.columnIndexesToExport)
            {
                TableCell cell = new TableCell();
                GridDataControlFieldCell cell2 = row.Controls[num] as GridDataControlFieldCell;
                if (this.grid.ExportingSettings.KeepColumnSettings)
                {
                    cell.Attributes["width"] = this.grid.Columns[num].Width;
                    cell.Attributes["align"] = this.grid.Columns[num].HeaderAlign;
                    if (!this.grid.Columns[num].Wrap)
                    {
                        cell.Attributes["nowrap"] = "nowrap";
                    }
                }
                if (!string.IsNullOrEmpty(this.grid.CssSettings.CSSExportHeaderCellStyle))
                {
                    cell.Attributes["style"] = this.grid.CssSettings.CSSExportHeaderCellStyle;
                }
                if (this.grid.ExportingSettings.ExportTemplates && !string.IsNullOrEmpty(this.grid.Columns[num].TemplateSettings.HeaderTemplateId))
                {
                    StringWriter writer = new StringWriter();
                    Html32TextWriter writer2 = new Html32TextWriter(writer);
                    cell2.Controls[0].Controls[0].RenderControl(writer2);
                    cell.Text = writer.ToString();
                }
                else
                {
                    cell.Text = ((HtmlContainer) cell2.Controls[0].Controls[0]).Text;
                }
                child.Controls.Add(cell);
            }
            this.grid.exportedGrid.Controls.Add(child);
            this.grid.OnRowExported(child, row as GridRow);
        }

        internal void ForceEnsureChildControls()
        {
            this.EnsureChildControls();
        }

        protected virtual string GetHeaderID()
        {
            return ("ob_" + this.grid.GridID + "HeaderContainer");
        }

        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
    }
}

